//********************************************************************
// 
//  file:  Utils.cs
// 
//  (C) Copyright 2010, Diomede Corporation
//  All rights reserved
// 
//  Use, modification, and distribution is subject to   
//  the New BSD License (See accompanying file license.txt).
// 
//********************************************************************

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Diomede.SDK
{
    /// <summary>
    /// Utility class. Contains helper methods for the application.
    /// </summary>
    public class Utilities
    {

        public static double MonetaryIntToDouble(int v)
        {
            return ((double)v) / 10000;
        }

        public static string MonetaryIntToCurrency(int v)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-us");
            return MonetaryIntToDouble(v).ToString("C", ci);
        }

        public static string GetFileMD5Hash(string filename)
        {
            string hash = GetHashFromFS(filename);
            if (!string.IsNullOrEmpty(hash))
                return hash;

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                md5.Initialize();
                int pos;
                byte[] buffer = new byte[3145728];
                while ((pos = fs.Read(buffer, 0, 3145728)) > 0)
                {
                    md5.TransformBlock(buffer, 0, pos, buffer, 0);
                }
                md5.TransformFinalBlock(buffer, 0, 0);
                fs.Close();
                hash = Convert.ToBase64String(md5.Hash);
                WriteHashToFS(filename, hash);
                return hash;
            }
        }

        public static string GetHashFromFS(string filename)
        {
            string path = string.Format("{0}.md5", filename);
            if (!File.Exists(path))
                return string.Empty;
            using (StreamReader fs = new StreamReader(path))
            {
                string res = fs.ReadToEnd();
                fs.Close();
                return res;
            }
        }

        public static void WriteHashToFS(string filename, string hash)
        {
            using (StreamWriter fs = new StreamWriter(string.Format("{0}.md5", filename)))
            {
                fs.Write(hash);
                fs.Flush();
                fs.Close();
            }
        }
    }
}
